/*
 * @Description: axios request
 * @Author: zhangguoliang
 * @Date: 2021-08-03 16:11:11
 * @LastEditors: wangru
 * @LastEditTime: 2023-08-18 09:53:07
 */

import axios from 'axios';
import { useUserStore } from '@/store/user.js';
import { projectDetailStore } from '@/store/projectDetail';
import { message } from 'ant-design-vue';
import Cookies from 'js-cookie';
const request = axios.create({
	baseURL: '',
	// timeout: 10000,
});
let firstLogout = true;
request.interceptors.request.use(
	(config) => {
		const { url = '', headers } = config;
		const token = Cookies.get('pricing_token');
		if (token && !config.headers.Authorization) {
			config.headers['Authorization'] = `bearer ${token}`;
		}
		const newHeaders = {
			...headers,
			PRODUCT_CODE: 'HZJT_YZJ_WEB',
			AGENCY_CODE: 'HZJT',
			'Content-Type': 'application/json',
		};

		return {
			...config,
			url: `${url}${url.includes('?') ? '&' : '?'}v=${Date.now()}`,
			headers: newHeaders,
		};
	},
	(err) => Promise.reject(err)
);

request.interceptors.response.use(
	(res) => {
		const UserStore = useUserStore();
		const projectDetail = projectDetailStore();

		const { data, status } = res;
		const mess =
			data.message && data.status !== 500 ? data.message : '网络请求错误';
		if (status >= 400 || data.status >= 400) {
			if (status === 400 || data.status === 400) {
				if (projectDetail.tabSelectName === '费用汇总') return data;
			}
			if (
				[401, 403].includes(status) ||
				[401, 403].includes(data.status)
			) {
				if (firstLogout) {
					firstLogout = false;
					message.error('请重新登陆！');
					setTimeout(() => {
						UserStore.logout();
						firstLogout = true;
					}, 1000);
				}
				return Promise.reject('请重新登陆！');
			}
			message.error(mess);
			return Promise.reject(mess);
		}
		return data;
	},
	(err) => Promise.reject(err)
);

export default request.request;
